﻿using System.Text.RegularExpressions;
using System.Security.Cryptography.X509Certificates;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Auth;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using AssetManageSystem.Model.AssetManage;

namespace AssetManageSystem.Controllers
{
    public class HomeController : BaseController
    {

        [AllRights]
        public IActionResult Index()
        {

            ViewData["title"] = "资产管理系统";
            return View();
        }

        [AllowAnonymous]
        public IActionResult PIndex()
        {
            return View();
        }

        [AllRights]
        [ActionDescription("FrontPage")]
        public IActionResult FrontPage()
        {

            return PartialView();
        }

        [AllRights]
        [ActionDescription("Layout")]
        public IActionResult Layout()
        {
            ViewData["debug"] = Wtm.ConfigInfo.IsQuickDebug;
            return PartialView();
        }

        [AllRights]
        public IActionResult UserInfo()
        {
            if (HttpContext.Request.Cookies.TryGetValue(CookieAuthenticationDefaults.CookiePrefix + AuthConstants.CookieAuthName, out string cookieValue))
            {
                var protectedData = Base64UrlTextEncoder.Decode(cookieValue);
                var dataProtectionProvider = HttpContext.RequestServices.GetRequiredService<IDataProtectionProvider>();
                var _dataProtector = dataProtectionProvider
                                        .CreateProtector(
                                            "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                                            CookieAuthenticationDefaults.AuthenticationScheme,
                                            "v2");
                var unprotectedData = _dataProtector.Unprotect(protectedData);

                string cookieData = Encoding.UTF8.GetString(unprotectedData);
                return JsonMore(cookieData);
            }
            else
                return JsonMore("No Data");
        }

        //首页条形图生成接口
        [AllRights]
        public IActionResult GetActionChart()
        {
            var areas = GlobaInfo.AllModule.Select(x => x.Area).Distinct();
            var data = new List<ChartData>();

            foreach (var area in areas)
            {
                var controllers = GlobaInfo.AllModule.Where(x => x.Area == area);
                data.Add(new ChartData
                {
                    Category = "Controllers",
                    Value = controllers.Count(),
                    Series = area?.AreaName ?? "Default"
                });
                data.Add(new ChartData
                {
                    Category = "Actions",
                    Value = controllers.SelectMany(x => x.Actions).Count(),
                    Series = area?.AreaName ?? "Default"
                });
            }
            var rv = data.ToChartData();
            return Json(rv);
        }

        //首页饼图数据接口（根据资产类型统计使用中的资产数量，然后生成饼图）
        [AllRights]
        public IActionResult GetAssetCountChart()
        {
            //声明一个Dictionary类型的变量
            var Dic = new Dictionary<string, int>();

            //声明一个变量datas，查询资产信息表表中正在使用的资产，先根据资产类型进行分组，然后根据类型进行统计
            var datas = DC.Set<AssetInfo>().Where(x => x.Status == Model.Enum.AsStatusEnum.OnUse)
            .GroupBy(x => x.Type.TypeName).Select(x => new { str = x.Key, sum = x.Count() });
            if (datas != null)
            {
                foreach (var d in datas)
                {
                    //使用上面查询到的数据填充变量Dic
                    Dic.Add(d.str, d.sum);
                }
            }
            var data = new List<ChartData>();

            foreach (var m in Dic)
            {
                data.Add(new ChartData
                {
                    Value = m.Value,
                    Category = m.Key,
                    Series = "Dic"
                });
            }
            var rv = data.ToChartData();
            return Json(rv);
        }

        /// <summary>
        /// 首页资产状态统计
        /// </summary>
        /// <returns></returns>
        [AllRights]
        public IActionResult GetAssetCount()
        {
            var Dic = new Dictionary<string, int>();

            var datas = DC.Set<AssetInfo>().GroupBy(x => x.Status).Select(x => new { str = x.Key.ToString(), sum = x.Count() });
            if (datas != null)
            {
                foreach (var d in datas)
                {
                        Dic.Add(d.str, d.sum);
                }
            }
            return Json(Dic);
        }

        public IActionResult GetSampleChart()
        {
            var data = new List<ChartData>();
            Random r = new Random();
            int maxi = r.Next(3, 10);
            int maxy = r.Next(3, 10);
            for (int i = 0; i < maxi; i++)
            {
                for (int j = 0; j < maxy; j++)
                {
                    data.Add(new ChartData
                    {
                        Category = "x" + i,
                        Value = r.Next(100, 1000),
                        ValueX = r.Next(200, 2000),
                        Series = "y" + j,
                        Addition = r.Next(100, 1000),

                    });
                }
            }
            var rv = data.ToChartData();
            return Json(rv);
        }

        /// <summary>
        /// 首页资产统计柱状图
        /// </summary>
        /// <returns></returns>
        [AllRights]
        public IActionResult GetAssetTypeCount()
        {
            var Dic = new Dictionary<string, int>();
            var data = new List<ChartData>();

            var datas = DC.Set<AssetInfo>().GroupBy(x => x.Type.TypeName).Select(x => new { str = x.Key, sum = x.Count()});
            if (datas != null)
            {
                foreach (var d in datas)
                {
                    data.Add(new ChartData
                    {
                        Value = d.sum,
                        Category = d.str,
                        Series = "Dic"
                    });
                }
            }
            var rv = data.ToChartData();
            return Json(rv);
        }
    }

}
